//
//  ChangePasswordViewController.m
//  SoutheastAsia
//
//  Created by rimi on 16/1/19.
//  Copyright © 2016年 zlj. All rights reserved.
//

#import "ChangePasswordViewController.h"
#import "AVOSCloud/AVOSCLoud.h"
#import "UserModel.h"

#define TEXT_HEIGHT 40
#define TEXT_WIDTH 220

#define BUTTON_LOCATION CGRectGetWidth(self.view.frame) / 2
@interface ChangePasswordViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UITextField *oldMmTextField;
@property (nonatomic, strong) UITextField *changeMmTextFiled;
@property (nonatomic, strong) UITextField *sureChangeMmTextField;
@property (nonatomic, strong) NSArray *arrayOfTextName;
@property (nonatomic, strong) UIImageView *backgroundImageView;
@property (nonatomic, strong) UIImageView *logoImageView;
@property (nonatomic, strong) UIButton *backLoginButton;

- (void)initilizeApperance;


@end
enum {
    TAG_BUTTON  = 110,
};
@implementation ChangePasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initilizeApperance];
    
}
#pragma mark - private method
- (void)initilizeApperance {
    

    [self.view addSubview:self.backgroundImageView];
    [self.view addSubview:self.logoImageView];
    [self.view addSubview:self.backLoginButton];
    [self.view addSubview:self.oldMmTextField];
    [self.view addSubview:self.changeMmextFiled];
    [self.view addSubview:self.sureChangeMmTextField];
    
    NSArray *buttonName = @[@"registerGo.png",@"registerCancel.png"];
    for (NSInteger index = 0; index < 2; index ++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = TAG_BUTTON + index;
        button.backgroundColor = [UIColor clearColor];
        [button setImage:[UIImage imageNamed:buttonName[index]] forState:UIControlStateNormal];
        button.bounds = CGRectMake(0, 0, BUTTON_LOCATION / 2, BUTTON_LOCATION / 8 + 10.0);
        if (index == 0) {
            button.center = CGPointMake(CGRectGetMidX(self.view.frame) - BUTTON_LOCATION / 2, CGRectGetMaxY(self.view.frame) - BUTTON_LOCATION / 4);
        } else {
            button.center = CGPointMake(CGRectGetMidX(self.view.frame) + BUTTON_LOCATION / 2, CGRectGetMaxY(self.view.frame) - BUTTON_LOCATION / 4);
        }
        [button addTarget:self action:@selector(controlOfChangePassword:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
}
#pragma mark -- system protocol
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 300);//键盘高度300
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}
#pragma mark - callback / action
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)controlOfChangePassword:(UIButton *)sender {
    switch (sender.tag - TAG_BUTTON) {
        case 0://确认按钮
        {
            
            [AVUser logInWithUsername:[UserModel defaultUesr].userName password:[UserModel defaultUesr].userPassword error:nil]; //请确保用户当前的有效登录状态
            
            
            if (![self.oldMmTextField.text isEqualToString:[UserModel defaultUesr].userPassword]) {
                
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"修改失败" message:@"旧密码错误" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
                return;
            }
            if (self.changeMmTextFiled.text.length < 8 || self.changeMmTextFiled.text.length > 16) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"修改失败" message:@"新密码长度需在8位到16位之间" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
                return;
            }
            if (![self.changeMmTextFiled.text isEqualToString:self.sureChangeMmTextField.text]) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"修改失败" message:@"新密码和确认密码不同" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
                return;
            }
            
            [[AVUser currentUser] updatePassword:self.oldMmTextField.text newPassword:self.changeMmTextFiled.text block:^(id object, NSError *error) {
                //处理结果
                if (!error) {
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"修改成功" message:@"" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        [self.navigationController popViewControllerAnimated:YES];
                    }];
                    [alertController addAction:cancelAction];
                    [self presentViewController:alertController animated:YES completion:nil];
                }
            }];
            
        }
            break;
        case 1://清空按钮
        {
            self.oldMmTextField.text = @"";
            self.changeMmTextFiled.text = @"";
            self.sureChangeMmTextField.text = @"";
        }
            break;
        default:
            break;
    }
}

- (void)backLoginButtonTaped:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - getter

- (NSArray *)arrayOfTextName {
    if (!_arrayOfTextName) {
        _arrayOfTextName = ({
            NSArray *array = @[@"请输入旧密码",@"请输入新密码",@"请确认新密码"];
            array;
        });
    }
    return _arrayOfTextName;
}

- (UITextField *)oldMmTextField {
    if (!_oldMmTextField) {
        _oldMmTextField = ({
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, TEXT_WIDTH , TEXT_HEIGHT)];
            textField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame) + 60);
            textField.borderStyle = UITextBorderStyleRoundedRect;
            textField.placeholder = self.arrayOfTextName[0];
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.delegate = self;
            textField.secureTextEntry = YES;
            textField;
        });
    }
    return _oldMmTextField;
}
- (UITextField *)changeMmextFiled {
    if (!_changeMmTextFiled) {
        _changeMmTextFiled = ({
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, TEXT_WIDTH , TEXT_HEIGHT)];
            textField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame) + 120);
            textField.borderStyle = UITextBorderStyleRoundedRect;
            textField.placeholder = self.arrayOfTextName[1];
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.delegate = self;
            textField.secureTextEntry = YES;
            textField;
        });
    }
    return _changeMmTextFiled;
}
- (UITextField *)sureChangeMmTextField {
    if (!_sureChangeMmTextField) {
        _sureChangeMmTextField = ({
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, TEXT_WIDTH , TEXT_HEIGHT)];
            textField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame) + 180);
            textField.borderStyle = UITextBorderStyleRoundedRect;
            textField.placeholder = self.arrayOfTextName[2];
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.delegate = self;
            textField.secureTextEntry = YES;
            textField;
        });
    }
    return _sureChangeMmTextField;
}
//背景
- (UIImageView *)backgroundImageView {
    if (!_backgroundImageView) {
        _backgroundImageView = ({
            UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"registerBackgroundImage.png"]];
            view.frame = CGRectMake(0, 0, CGRectGetMaxX(self.view.frame), CGRectGetMaxY(self.view.frame));
            view;
        });
    }
    return _backgroundImageView;
}
//logo
- (UIImageView *)logoImageView {
    if (!_logoImageView) {
        _logoImageView = ({
            UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"title.png"]];
            view.bounds = CGRectMake(0, 0, CGRectGetMaxX(self.view.bounds), 400);
            view.center = self.view.center;
            
            view;
        });
    }
    return _logoImageView;
}
- (UIButton *)backLoginButton {
    if (!_backLoginButton) {
        _backLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backLoginButton.frame = CGRectMake(5, 40, 40, 40);
        [_backLoginButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
        [_backLoginButton addTarget:self action:@selector(backLoginButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backLoginButton;
}
@end
